/**
 * 复制文案到粘贴板
 * @param input 需要复制的内容
 * @param target 目标 HTML 元素，默认为 document.body
 * @returns 返回布尔值，表示复制操作是否成功
 */
export const copyTextToClipboard = (input: string, target: HTMLElement = document.body) => {
  const element = document.createElement('textarea')
  const previouslyFocusedElement = document.activeElement as HTMLElement

  element.value = input
  element.setAttribute('readonly', '') // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘，同时将 textarea 移出可视区域
  element.style.contain = 'strict'
  element.style.position = 'absolute'
  element.style.left = '-9999px'

  const selection = document.getSelection()
  let originalRange
  if (selection && selection.rangeCount > 0) {
    originalRange = selection.getRangeAt(0)
  }

  target?.append(element)
  element.select()

  element.selectionStart = 0
  element.selectionEnd = input.length

  let isSuccess = false
  try {
    isSuccess = document.execCommand('copy')
  } catch (error: any) {
    throw new Error(error)
  }

  element.remove()

  if (originalRange && selection) {
    selection.removeAllRanges()
    selection.addRange(originalRange)
  }

  if (previouslyFocusedElement) {
    previouslyFocusedElement.focus()
  }
  return isSuccess
}
